# -*- coding: utf-8 -*-
import time
from selenium import webdriver
import smtplib
from email.mime.text import MIMEText

# 只需修改下面三项即可 学号 密码 打卡网址
username = "你的学号"
password = "你的密码"
url = "www.baidu.com"

# 下面是每次填报的时候几个需要填写的地方，F12找到这些位置的 full XPath
position = "/html/body/form/div/div/div[1]/div[8]/div[2]/div[1]/p/a"  # 获取位置按钮
submit = "/html/body/form/div/div/div[2]/a"  # 提交按钮
passwordXpath = "/html/body/div/div[3]/div[2]/div/div[2]/div/div[1]/form/div[3]/div/input[1]"

# 模拟登陆打卡
def do_login(driver):
    try:
        # 将窗口最大化
        driver.maximize_window()
        # 找到登录框 输入账号密码
        driver.find_element_by_name('username').send_keys(username)
        driver.find_element_by_xpath(passwordXpath).send_keys(password)
        driver.find_element_by_id('dl').click()  # 点击登录
        # 延时一秒
        time.sleep(1)

        # 获取位置
        driver.find_element_by_xpath(position).click()

        # 点击最后的提交按钮
        driver.find_element_by_xpath(submit).click()

    except Exception as e:
        print("出现错误了",e)

def send_email():
    # 设置服务器所需信息
    # qq邮箱服务器地址
    mail_host = 'smtp.qq.com'
    # qq用户名
    mail_user = '你的邮箱'
    # 密码(部分邮箱为授权码)
    mail_pass = '申请的授权码'
    # 邮件发送方邮箱地址
    sender = '发送者邮箱'
    # 邮件接受方邮箱地址，注意需要[]包裹，这意味着你可以写多个邮件地址群发
    receivers = ['接受者邮箱']

    # 设置email信息
    # 邮件内容设置
    message = MIMEText('今日份打卡成功！！！', 'plain', 'utf-8')
    # 邮件主题
    message['Subject'] = '自动化打卡成功'
    # 发送方信息
    message['From'] = sender
    # 接受方信息
    message['To'] = receivers[0]

    # 登录并发送邮件
    try:
        smtpObj = smtplib.SMTP_SSL(mail_host)
        # 连接到服务器
        smtpObj.connect(mail_host, 465)
        # 登录到服务器
        smtpObj.login(mail_user, mail_pass)
        # 发送
        smtpObj.sendmail(sender, receivers, message.as_string())
        # 退出
        smtpObj.quit()
        print('发送邮件成功')
    except smtplib.SMTPException as e:
        print('发送邮件失败', e)

if __name__ == '__main__':
    # 模拟浏览器打开网站
    driver = webdriver.Chrome()
    driver.get(url)
    # 登录并打卡
    do_login(driver)
    # 给邮箱发送邮件
    send_email()
    print("打卡结束")
    time.sleep(1)  # 终端给你时间确认已经打卡成功
    driver.quit()
